# -*- coding: utf-8 -*-

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from channels.generic.websocket import AsyncWebsocketConsumer


class ConsoleConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.user_id = self.scope['url_route']['kwargs']['user_id']
        self.func_name = self.scope['url_route']['kwargs']['func_name']
        self.group_name = 'console_%s_%s' % (self.func_name, self.user_id)

        await self.channel_layer.group_add(self.group_name, self.channel_name)
        # 连接到WebSocket
        await self.accept()

    async def disconnect(self, close_code):
        # 断开WebSocket连接
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    async def console_message(self, event):
        # 处理发送的消息
        message = event.get('message')
        if message:
            await self.send(text_data=message)


def send_msg(func_name, user_id, message):
    """
    从Channels的外部发送消息给Channel
    """
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'console_{}_{}'.format(func_name, user_id),  # 构造Channels组名称
        {
            "type": "console_message",
            "message": message,
        }
    )
